/**
 * 
 */
package com.fclassroom.logger.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Consts.CursorMode;
import com.aliyun.openservices.log.common.LogContent;
import com.aliyun.openservices.log.common.LogGroupData;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.request.ListLogStoresRequest;
import com.aliyun.openservices.log.request.ListTopicsRequest;
import com.aliyun.openservices.log.request.PutLogsRequest;
import com.aliyun.openservices.log.response.BatchGetLogResponse;
import com.aliyun.openservices.log.response.GetCursorResponse;
import com.aliyun.openservices.log.response.GetLogsResponse;
import com.aliyun.openservices.log.response.ListShardResponse;
import com.aliyun.openservices.log.response.PutLogsResponse;
import com.fclassroom.logger.iInterface.IAliLogService;
import com.fclassroom.logger.util.JasonUtil;
import com.jason.framework.util.DateUtil;
import com.jason.framework.util.JsonUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author zb
 * @Time 2017年4月26日 下午5:05:36
 */
@Service("aliLogService")
public class AliLogService implements IAliLogService {
	private Logger logger = LogManager.getLogger();
	private final String endpoint = "cn-shanghai.log.aliyuncs.com";// 选择与上面步骤创建
																	// project
																	// 所属区域匹配的Endpoint
	private final String accessKeyId = "LTAIDuuufwReFcus";// 使用您的阿里云访问密钥AccessKeyId
	private final String accessKeySecret = "tDNBq1gRwVVUIHuxT1OUNbpsvYb9oR";// 使用您的阿里云访问密钥AccessKeySecret
	// private final String project = "jike-test";// 項目名稱
	// private final String logstore = "jike-test";// 日志庫名称

	@Override
	public void insertLogToDB(String logMsg) {
		if (StringUtils.isNotBlank(logMsg)) {

		}
	}

	@Override
	public void insertLogToSLS(Client client, String project, String logstore, String topic, String source,
			String logMsg) {
		try {
			if (client == null) {
				// 构建一个客户端实例
				client = new Client(endpoint, accessKeyId, accessKeySecret);
			}
			// 写入日志
			// 连续发送 10 个数据包，每个数据包有 10 条日志
			Vector<LogItem> logGroup = new Vector<LogItem>();
			LogItem logItem = new LogItem((int) (new Date().getTime() / 1000));

			logItem.PushBack(DateUtil.getNow(DateUtil.YYYY_MM_DD_HH_MM_SS), logMsg);
			logGroup.add(logItem);
			PutLogsRequest req2 = new PutLogsRequest(project, logstore, topic, source, logGroup);
			PutLogsResponse putLogsResponse = client.PutLogs(req2);
			System.out.println(putLogsResponse);
			/*
			 * 发送的时候也可以指定将数据发送至有一个特定的 shard，只要设置 shard 的 hashkey，则数据会写入包含该
			 * hashkey 的 range 所对应的 shard，具体 API 参考以下接口： public PutLogsResponse
			 * PutLogs( String project, String logStore, String topic,
			 * List<LogItem> logItems, String source, String shardHash // 根据
			 * hashkey 确定写入 shard，hashkey 可以是 MD5(ip) 或 MD5(id) 等 ) throws
			 * LogException;
			 */

		} catch (Exception e) {
			logger.error("插入sls数据库出错：{}", e.getMessage());
			e.printStackTrace();
		}

	}

	@Override
	public void insertLogListToSLS(Client client, String project, String logstore, String topic, String source,
			String logMsg) {
		try {
			if (client == null) {
				// 构建一个客户端实例
				client = new Client(endpoint, accessKeyId, accessKeySecret);
			}
			List<Map<String, Object>> msgList = JsonUtil.jsonToObject(logMsg, List.class);
			String msg = "";
			for (Map<String, Object> msgmap : msgList) {
				Vector<LogItem> logGroup = new Vector<LogItem>();
				msg = msgmap.get("msg").toString();
				if (StringUtils.isNotBlank(msg)) {
					LogItem log = new LogItem();
					log.PushBack(DateUtil.getNow(DateUtil.YYYY_MM_DD_HH_MM_SS), msg);
					logGroup.add(log);
				}
				PutLogsRequest req2 = new PutLogsRequest(project, logstore, topic, source, logGroup);
				PutLogsResponse response = client.PutLogs(req2);
				System.out.println(response);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	@Override
	public ArrayList<String> getLogStores(Client client, String project) {
		if (client == null) {
			client = new Client(endpoint, accessKeyId, accessKeySecret);
		}
		ListLogStoresRequest req1 = new ListLogStoresRequest(project, 0, 100, "");
		ArrayList<String> logStores = null;
		try {
			logStores = client.ListLogStores(req1).GetLogStores();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("ListLogs:" + logStores.toString() + "\n");
		return logStores;
	}

	@Override
	public ArrayList<String> getLogTopics(Client client, String project, String logstore) {
		if (client == null) {
			client = new Client(endpoint, accessKeyId, accessKeySecret);
		}
		ListTopicsRequest req1 = new ListTopicsRequest(project, logstore);
		ArrayList<String> logTopics = null;
		try {
			logTopics = client.ListTopics(req1).GetTopics();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("ListLogs:" + logTopics.toString() + "\n");
		return logTopics;
	}

	@Override
	public void getLogItem(Client client, String project, String logstore, int shard_id, String time) {
		if (client == null) {
			client = new Client(endpoint, accessKeyId, accessKeySecret);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date fromTime = null;
		try {
			fromTime = sdf.parse(time);
			ListShardResponse shardresponse = client.ListShard(project, logstore);
			System.out.println("shard size::::::" + shardresponse.GetShards().size());
			GetCursorResponse cursorRes = client.GetCursor(project, logstore, shard_id, fromTime.getTime());
			String beginCursor = cursorRes.GetCursor();
			cursorRes = client.GetCursor(project, logstore, shard_id, CursorMode.END);
			String endCursor = cursorRes.GetCursor();
			String curCursor = beginCursor;
			int index = 0;
			while (curCursor.equals(endCursor) == false) {
				int loggroup_count = 2; // 每次读取两个 loggroup
				BatchGetLogResponse logDataRes = client.BatchGetLog(project, logstore, shard_id, loggroup_count,
						curCursor);
				List<LogGroupData> logGroups = logDataRes.GetLogGroups();
				for (LogGroupData logGroup : logGroups) {
					System.out.println("-----第" + (++index) + "条------");
					System.out.println("Source:" + logGroup.GetSource());
					System.out.println("Topic:" + logGroup.GetTopic());
					for (LogItem log : logGroup.GetAllLogs()) {
						System.out.println("LogTime:" + sdf.format(new Date(((long) log.GetTime()) * 1000)));
						List<LogContent> contents = log.GetLogContents();
						for (LogContent content : contents) {
							System.out.println("key:" + content.GetKey() + "\nvalue=" + content.GetValue());
						}
					}
				}
				String next_cursor = logDataRes.GetNextCursor();
				System.out.println("The Next cursor:" + next_cursor);
				curCursor = next_cursor;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getLogsByTopic(Client client, String project, String logstoreName, String start, String end,
			String topic, String query) {
		if (client == null) {
			client = new Client(endpoint, accessKeyId, accessKeySecret);
		}

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date fromTime = null;
			Date endTime = null;
			try {
				endTime = sdf.parse(end);
				fromTime = sdf.parse(start);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int startValue = Integer.valueOf(String.valueOf(fromTime.getTime() / 1000));
			int endValue = Integer.valueOf(String.valueOf(endTime.getTime() / 1000));
			GetLogsResponse logresponse = client.GetLogs(project, logstoreName, startValue, endValue, topic, query);
			ArrayList<QueriedLog> list = logresponse.GetLogs();
			LogItem logitem = null;
			int index = 0;
			for (QueriedLog log : list) {
				System.out.println("-----第" + (++index) + "条------");
				logitem = log.GetLogItem();
				List<LogContent> contents = logitem.GetLogContents();
				for (LogContent content : contents) {
					System.out.println("key:" + content.GetKey() + "\nvalue=" + content.GetValue());
//					String value = content.GetValue();
//					String jsonStr = JasonUtil.toJson(value);
//					System.out.println("json:" + jsonStr);
//					// 保存日志数据到数据库
//					JSONObject json = JSONObject.fromObject(jsonStr);
//					JSONArray obj = (JSONArray) json.get("exception");
//					String val = (String) ((JSONObject) obj.get(0)).get("exceptiontype");
//					System.out.println(val);

				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
